﻿
using Autofac;
using Autofac.Integration.Mvc;

using System.Linq;
using System.Reflection;
namespace MyFileView.Core
{
    public static class AutoFacConfig
    {
        public static AutofacDependencyResolver Register(ContainerBuilder builder)
        {
            var register = typeof(RegisterAutofac);

            //  var builder = new ContainerBuilder();
            var assembly = Assembly.GetExecutingAssembly();
            //typeof(RegisterAutofac).IsAssignableFrom(x)
            //  var types =  assembly.GetTypes().Where(t => t.IsClass && !t.IsAbstract && t.GetInterfaces().Contains(register)).ToArray();

            builder.RegisterAssemblyTypes(assembly).Where(t => t.IsClass && !t.IsAbstract && t.GetInterfaces().Contains(register))
             .AsSelf()
             .AsImplementedInterfaces()
             .InstancePerDependency();



            //  var assembly = Assembly.GetExecutingAssembly();
            // builder.RegisterTypes(assembly);
            //   .AsImplementedInterfaces()  //是以接口方式进行注入
            //.InstancePerRequest()       //每次http请求
            //.PropertiesAutowired();
            //   builder.RegisterTypes(assembly.GetTypes());//
            var container = builder.Build();
            return new AutofacDependencyResolver(container);
            // .AsImplementedInterfaces()  //是以接口方式进行注入
            //.InstancePerRequest()
            //.InstancePerLifetimeScope()//每次http请求
            //.PropertiesAutowired();


            //1、无接口类注入
            //builder.RegisterType<BLL.newsClassBLL>().AsSelf().InstancePerRequest().PropertiesAutowired();


            //2、有接口类注入
            //注入BLL，UI中使用
            //var res = Assembly.GetExecutingAssembly();
            //builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
            //    .AsImplementedInterfaces()  //是以接口方式进行注入
            //    .InstancePerRequest()  
            //    .InstancePerLifetimeScope()//每次http请求
            //    .PropertiesAutowired();     //属性注入

            //注入DAL，BLL层中使用
            //builder.RegisterAssemblyTypes(typeof(DAL.BaseDAL<>).Assembly).AsImplementedInterfaces()
            //    .InstancePerRequest().PropertiesAutowired();     //属性注入

            //Cache的注入，使用单例模式
            //builder.RegisterType<RedisCacheManager>()
            //    .As<ICacheManager>()
            //    .SingleInstance()
            //    .PropertiesAutowired();

            //移除原本的mvc的容器，使用AutoFac的容器，将MVC的控制器对象实例交由autofac来创建


        }
    }
}
